package com.misc.tunewsreader;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.util.Pair;

public class NNTPArticleHeader {
	private long t_id;
	private int read;
	private HashMap<String, String> map;
	static final String[] headers_to_save = { "Date", "Subject", "From",
			"References", "Message-ID", "Content-Type" };

	public NNTPArticleHeader(List<String> data, long id, int is_read) {
		if (data == null)
			return;
		t_id = id;
		read = is_read;
		String last_key = "";

		// TODO: strip unnecessary headers to save space
		map = new HashMap<String, String>();
		String key, value;

		for (int i = 0; i < data.size(); i++) {
			Pair<String, String> tuple = parseHeaderLine(data.get(i), last_key);
			key = tuple.first;
			value = tuple.second;

			// decode subject and author (umlauts)
			if (key.equals("Subject") || key.equals("From")) {
				value = NNTPClient.decodeText(value);
			}

			boolean do_save = false;
			for (int j = 0; j < headers_to_save.length; j++) {
				if (headers_to_save[j].equals(key)) {
					do_save = true;
					break;
				}
			}

			if (do_save) {
				last_key = key;
				if (map.containsKey(key)) {
					map.put(key, map.get(key) + value);
				} else {
					map.put(key, value);
				}
			}
		}

		// format date
		map.put("DateDisplay", NNTPClient.convertDate(map.get("Date")));
		map.put("DateSortable", NNTPClient.convertDateSortable(map.get("Date")));
		// parse author name
		String author = getAuthor().replaceAll("<[^>]*>", "").trim();
		if (author.startsWith("\"") && author.endsWith("\""))
			author = author.substring(1, author.length() - 1).trim();
		map.put("AuthorName", author);
	}

	public static Pair<String, String> parseHeaderLine(String line,
			String last_key) {
		String key = "", value = "";
		int pos = line.indexOf(": ");
		if (pos == -1) {
			if (!last_key.equals("")) {
				key = last_key;
				value = line.trim();
			}
		} else {
			key = line.substring(0, pos).trim();
			value = line.substring(pos + 2).trim();
		}
		return new Pair<String, String>(key, value);
	}

	public static Pair<String, String> parseHeaderLine(String line) {
		return parseHeaderLine(line, "");
	}

	public String getSubject() {
		// return NNTPClient.decodeText(map.get("Subject"));
		return map.get("Subject");
	}

	public String getAuthor() {
		// return NNTPClient.decodeText(map.get("From"));
		return map.get("From");
	}

	public String getAuthorName() {
		return map.get("AuthorName");
	}

	public String getMessageID() {
		return map.get("Message-ID");
	}

	public String getDate() {
		return get("DateDisplay");
	}

	public String getDateSortable() {
		return get("DateSortable");
	}

	public String getCharset() {
		if (!map.containsKey("Charset")) {
			// get charset
			String charset = "UTF-8";
			String cont = map.get("Content-Type");
			if (cont != null) {
				if (cont.toLowerCase().lastIndexOf("charset=") != -1) {
					charset = cont.substring(
							cont.toLowerCase().lastIndexOf("charset=") + 8)
							.trim();
					if (charset.indexOf(';') != -1) {
						charset = charset.substring(0, charset.indexOf(';'))
								.trim();
					}
				}
			}
			// remove quotes around charset
			if (charset.startsWith("\"") && charset.endsWith("\""))
				charset = charset.substring(1, charset.length() - 1).trim();
			map.put("Charset", charset);
			return charset;
		} else {
			return get("Charset");
		}
	}

	public long getThreadId() {
		return t_id;
	}

	public String get(String key) {
		if (map.containsKey(key))
			return map.get(key);
		else
			return "";
	}

	public String getAsString() {
		String res = "";
		Iterator<HashMap.Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			HashMap.Entry<String, String> pairs = (HashMap.Entry<String, String>) it
					.next();
			res += pairs.getKey() + ": " + pairs.getValue() + "\r\n";
		}
		return res;
	}

	public boolean isParent() {
		return !map.containsKey("References");
	}

	public void setParent() {
		if (map.containsKey("References"))
			map.remove("References");
	}

	public boolean isRead() {
		return read != 0;
	}

	public void setRead(boolean is_read) {
		if (is_read)
			read = 1;
		else
			read = 0;

		NNTPClient.markPostRead(t_id, is_read);
	}
}
